package sjd.ahsj.springbootmybatisplusoracle.controller;


import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import sjd.ahsj.springbootmybatisplusoracle.entity.IAttachment;
import sjd.ahsj.springbootmybatisplusoracle.interceptor.IgnoreAuth;
import sjd.ahsj.springbootmybatisplusoracle.model.ReturnObject;
import sjd.ahsj.springbootmybatisplusoracle.service.IIAttachmentService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Random;

/**
 * <p>
 * 附件 前端控制器
 * </p>
 *
 * @author zhanghaogao
 * @since 2018-11-13
 */
@RestController
@RequestMapping("/iAttachment")
public class IAttachmentController {
    @Autowired
    private IIAttachmentService iiAttachmentService;

    /**
     * 文件路径
     */
    @Value("${file_address}")
    private String storePath;

    /**
     * 上传文件
     */
    @IgnoreAuth
    @ApiOperation("附件上传")
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public ReturnObject<IAttachment> upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            // 务必，防止返回文件名是乱码
            response.setCharacterEncoding("utf-8");
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iter = multipartRequest.getFileNames();

            while (iter.hasNext()) {
                MultipartFile file = multipartRequest.getFile(iter.next());
                IAttachment info = new IAttachment();


                if (file.isEmpty()) {
                    return new ReturnObject(1, "上传文件不能为空");
                }


                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
                String ymd = sdf.format(new Date());


                String savePath = storePath;

                /**
                 *  文件大小
                 */
                Long fileSize = file.getSize();

                info.setSize(fileSize.toString());
                if (fileSize > 100000000) {
//            throw new Exception("上传失败：文件大小不能超过10M");
                    return new ReturnObject(1, "上传失败：文件大小不能超过100M");
                }

                /**
                 * 得到文件名称
                 */
                String fileName = file.getOriginalFilename();
                info.setOriginalName(fileName);

                String newFileName = "";
                String fileExt = "";

                String saveFileName = ymd;

                savePath += File.separator + ymd + File.separator;
                File dirFile = new File(savePath);
                if (!dirFile.exists()) {
                    dirFile.mkdirs();
                }


                if (fileSize > 0) {
                    try {
                        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                        /**
                         *  文件后缀
                         */
                        fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();


                        info.setFileExt(fileExt);
                        /**
                         * 重定义文件名
                         */
                        newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;

                        info.setAttName(newFileName);
                        SaveFileFromInputStream(file.getInputStream(), savePath, newFileName);


                    } catch (IOException e) {
                        e.printStackTrace();
                        return null;
                    }
                } else {
                    return new ReturnObject(1, "上传失败：上传文件不能为空");
                }


                /**
                 * 保存入库
                 */
                saveFileName += File.separator + newFileName;

                info.setAddress(saveFileName);
                iiAttachmentService.insert(info);

                return new ReturnObject(0, "上传成功", info);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnObject(1, "系统偷懒了");

        }
        return new ReturnObject(1, "系统偷懒了");
    }

    public void SaveFileFromInputStream(InputStream stream, String path, String filename) throws IOException {
        FileOutputStream fs = new FileOutputStream(path + filename);
        byte[] buffer = new byte[1024 * 1024];
        int bytesum = 0;
        int byteread = 0;
        while ((byteread = stream.read(buffer)) != -1) {
            bytesum += byteread;
            fs.write(buffer, 0, byteread);
            fs.flush();
        }
        fs.close();
        stream.close();
    }

}

